import {
  getUserInfo
} from '@/api/login'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import store from '@/store'

const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    setting: {
      articlePlatform: []
    },
    groupIds: [],
    elements: []
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_EMAIL: (state, email) => {
      state.email = email
    },
    SET_MOBILE: (state, mobile) => {
      state.mobile = mobile
    },
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_GROUPID: (state, roles) => {
      state.groupIds = []
      if (roles && roles.length > 0) {
        roles.map(item => {
          state.groupIds.push(item.groupId)
        })
      }
    },
    SET_ELEMENTS: (state, elements) => {
      state.elements = elements
    }
  },

  actions: {

    // 获取用户信息
    GetUserInfo({
      commit
    }) {
      return new Promise((resolve, reject) => {
        getUserInfo(window.localStorage.groupId).then(response => {
          if (!response) { // 由于mockjs 不支持自定义状态码只能这样hack
            reject('error')
          }
          const data = response.data

          // 问题单 12580 遍历不到当前 groupId 则返回首页
          if (!data.roles || !data.roles.length) {
            return location.href = window.env.factoryHref
          }
          
          commit('SET_GROUPID', data.roles)
          let localGroupId = window.localStorage.getItem('groupId')
          let storeGroupIds = store.getters.groupIds
          if (storeGroupIds && storeGroupIds.length && localGroupId) {
            if (storeGroupIds.indexOf(localGroupId) < 0) {
              return location.href = window.env.factoryHref
            }
          }

          if (data.menus && data.menus.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', data.menus)
          } else {
            console.log('---- getInfo: menus must be a non-null array !')
          }

          if (data.elements && data.elements.length > 0) {
            let elements = data.elements.map(item => item.code)
            commit('SET_ELEMENTS', elements)
          } else {
            console.log('---- getInfo: elements must be a non-null array !')
          }

          commit('SET_NAME', data.name)
          commit('SET_USER', data.username)
          commit('SET_EMAIL', data.email)
          commit('SET_MOBILE', data.mobilePhone)
          commit('SET_ID', data.id)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resolve()
        // logout(state.token).then((res) => {
        //   commit('SET_TOKEN', '')
        //   commit('SET_ROLES', [])
        //   removeToken()
        //   resolve(res)
        // }).catch(error => {
        //   reject(error)
        // })
      })
    },

    // 前端 登出
    FedLogOut({
      commit
    }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    // 动态修改权限
    ChangeRoles({
      commit
    }, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        getUserInfo(role).then(response => {
          const data = response
          commit('SET_ROLES', data.roles)
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          resolve()
        })
      })
    }
  }
}

export default user